<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <select name="" id="province">
        <option value="">请选择</option>
    </select>

    <select name="" id="city">
        <option value="">请选择</option>
    </select>

    <select name="" id="area">
        <option value="">请选择</option>
    </select>


    <script>


        const oPro = document.querySelector('#province');
        const oCity = document.querySelector('#city');
        const oArea = document.querySelector('#area');



        let data;   // 获取数据
        let cityArr;



        // 先请求到数据
        const xhr = new XMLHttpRequest();
        xhr.open('get', '../data/cityData.json', true);
        xhr.send();
        xhr.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
                data = this.responseText;
                data = JSON.parse(data);
                console.log(data);

                // 渲染省
                renderPro(data);

            }
        }




        // 省发生改变
        oPro.onchange = function () {


            oArea.innerHTML = '<option value="">请选择</option>'   // *******************



            // console.log(this.value);
            const res = data.find(item => item.pro === this.value);
            // console.log(res);
            if (res) {
                cityArr = res.children;
                console.log(cityArr);

                let html = '<option value="">请选择</option>';
                cityArr.forEach(item => {
                    html += `<option value="${item.city}">${item.city}</option>`
                })
                oCity.innerHTML = html

            }
            else {
                // 说明点击的是请选择
                oCity.innerHTML = '<option value="">请选择</option>';
            }
        }




        oCity.onchange = function () {
            console.log(this.value);
            const res = cityArr.find(item => item.city === this.value);
            console.log(res);
            if (res) {
                const areaArr = res.children;
                console.log(areaArr);
                let html = '<option value="">请选择</option>';
                areaArr.forEach(item => {
                    html += `<option value="${item}">${item}</option>`
                })
                oArea.innerHTML = html
            }
            else {
                oArea.innerHTML = '<option value="">请选择</option>'
            }
        }













        // 渲染省
        function renderPro(data) {
            let html = '<option value="">请选择</option>';
            data.forEach(item => {
                html += `<option value="${item.pro}">${item.pro}</option>`
            })
            oPro.innerHTML = html
        }






    </script>


</body>

</html>